#include "core_thread.h"
#include "core_log.h"


CoreThread::CoreThread():isRuning(false), threadname("default")
{

}


CoreThread::~CoreThread()
{

}

void CoreThread::start(std::string name, ThreadCall oncreate, ThreadCall onrun, ThreadCall ondestory)
{
	this->isRuning = true;
	this->threadname = name;
	if (oncreate)
	{
		this->onCreate = oncreate;
	}
	if (onrun)
	{
		this->onRun = onrun;
	}
	if (ondestory)
	{
		this->onDestory = ondestory;
	}

	std::thread t(std::mem_fn(&CoreThread::onWork), this);
	t.detach();
}

void CoreThread::stop()
{
	std::lock_guard<std::mutex> lock(mymutex);
	if (this->isRuning)
	{
		this->isRuning = false;
		this->semaphore.wait();
	}
}

void CoreThread::exit()
{
	std::lock_guard<std::mutex> lock(mymutex);
	if (this->isRuning)
	{
		this->isRuning = false;
	}
}

bool CoreThread::running()
{
	return this->isRuning;
}

void CoreThread::onWork()
{
	//std::cout << "threadname:" << this->threadname << " threadid:" << std::this_thread::get_id() << std::endl;
	if (this->onCreate)
	{
		this->onCreate(this);
	}
	if (this->onRun)
	{
		this->onRun(this);
	}
	if (this->onDestory)
	{
		this->onDestory(this);
	}
	this->semaphore.wakeup();
}

